package com.example.myx5;


import static com.example.myx5.app.App.APP_HOME;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.myx5.utils.DownLoadUtils;
import com.example.myx5.utils.SPUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.OnDownloadListener;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.JsonMap;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialogx.dialogs.BottomDialog;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.kongzue.kongzueupdatesdk.v3.UpdateUtil;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebIconDatabase;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebStorage;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.sdk.WebViewDatabase;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class HomeActivity extends AppCompatActivity {

    WebView mWebView;
    ValueCallback<Uri> mUploadMessage;
    private static final int REQUEST_CHOOSE = 2;
    ValueCallback<Uri[]> mUploadMessagesAboveL;

    private boolean openPhotos = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }

        try {
            if(getIntent().getStringExtra("canCLean").equals("1")){
                cleanCache();
            }

        }catch (Exception e){

        }

        mWebView = findViewById(R.id.forum_context);

        mWebView.setOnLongClickListener(new View.OnLongClickListener(){

            @Override
            public boolean onLongClick(View v) {

                final WebView.HitTestResult hitTestResult = mWebView.getHitTestResult();
                // 如果是图片类型或者是带有图片链接的类型
                if (hitTestResult.getType() == android.webkit.WebView.HitTestResult.IMAGE_TYPE ||
                        hitTestResult.getType() == android.webkit.WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

                    final String pic = hitTestResult.getExtra();//获取图片

                    CharSequence[] menuList = new CharSequence[2];
                    menuList[0] = "保存图片";
                    menuList[1] = "取消";

                    BottomMenu.show(menuList)
                            .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                                @Override
                                public boolean onClick(BottomMenu dialog, CharSequence text, int index) {

                                    if (index ==0 ){
                                        String albumPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();

                                        File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ceshi");
                                        String fileNamePath = albumPath+ "/" + System.currentTimeMillis() + "_" + new Random().nextInt(Integer.MAX_VALUE) + ".jpg";
//判断当前安卓版本是否大于10
                                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {



                                        }


//                                        File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ceshi");

                                       /*  new Thread(new Runnable() {
                                             @Override
                                             public void run() {
                                                 DownLoadUtils.getInstance().download(HomeActivity.this, pic, fileNamePath, "image/jpg");
                                             }
                                         }).start();
*/
                                        HttpRequest.DOWNLOAD(
                                                HomeActivity.this,pic,
                                                new File(fileNamePath),
                                                new OnDownloadListener() {
                                                    @Override
                                                    public void onDownloadSuccess(File file) {

                                                        runOnUiThread(new Runnable() {
                                                            @Override
                                                            public void run() {

                                                                TipDialog.show(HomeActivity.this, "下载成功,文件保存到"+file.getPath(), TipDialog.TYPE.SUCCESS);
                                                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                                                Uri uri = Uri.fromFile(file);
                                                                intent.setData(uri);
                                                                HomeActivity.this.sendBroadcast(intent);
                                                                try {

                                                                    // 通知系统多媒体扫描该文件，否则会导致拍摄出来的图片或者视频没有及时显示到相册中，而需要通过重启手机才能看到
                                                                    MediaScannerConnection.scanFile(HomeActivity.this, new String[]{file.getAbsolutePath()}, null, null);

                                                                    //说明第一个参数上下文，第二个参数是文件路径例如：/storage/emulated/0/1621832516463_1181875151.mp4 第三个参数是文件类型，传空代表自行根据文件后缀判断刷新到相册
                                                                    MediaScannerConnection.scanFile(HomeActivity.this, new String[]{file.getPath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                                                                        @Override
                                                                        public void onScanCompleted(String path, Uri uri) {
                                                                            //刷新成功的回调方法
                                                                            Log.d("资源刷新成功路径为", path);
                                                                        }
                                                                    });

                                                                } catch (Exception e) {
                                                                    e.printStackTrace();
                                                                }

                                                            }
                                                        });
                                                    }
                                                    @Override
                                                    public void onDownloading(int progress) {
//                                            psgDownload.setProgress(progress);
                                                        WaitDialog.show(HomeActivity.this, "请稍候...");
                                                    }
                                                    @Override
                                                    public void onDownloadFailed(Exception e) {
//                                            Toast.makeText(HomeActivity.this, "图片保存失败", Toast.LENGTH_SHORT);


                                                        TipDialog.show(HomeActivity.this, "下载失败，请重试！", TipDialog.TYPE.WARNING);
                                                    }
                                                }
                                        );
                                    }

                                    return false;
                                }
                            });		//指定已选择的位置



                }
                return false;
            }

        });

        XXPermissions.with(this)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                //.constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(Permission.Group.STORAGE)

                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });
        checkUpdata();
        initWeb();
    }



    private void checkUpdata() {

//        api/app/upgrade
        HttpRequest.POST(HomeActivity.this, APP_HOME+"/api/app/upgrade",  new Parameter().add("access_token", (String) SPUtils.get(this,"token","0")),new Parameter().add("access_token", (String) SPUtils.get(this,"token","0")), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {

                if (error == null) {
                    Log.d("respione22222",response+"");
//                    {"code":1,"msg":"","time":1595944972,"data":"88bb4d3121fbea9197b9b73d54e02921"}
                    JsonMap data = JsonMap.parse(response);
                    if(data.getInt("code")==1){
                        JsonMap dValue = data.getJsonMap("data");
                        String appurl = dValue.getString("appurl");
                        String content = dValue.getString("content");
                        if(appurl.equals("0")){
                            return;
                        }
                        try {
                            if(!dValue.getString("version").equals(getVersionName())){

                             /*   AllenVersionChecker
                                        .getInstance()

                                        .downloadOnly(
                                                UIData.create().setDownloadUrl(appurl)
                                                        .setContent("版本更新")
                                                        .setTitle("升级提醒")
                                        )
                                        .executeMission(HomeActivity.this);
*/

                                if (!dValue.getString("version").equals(getVersionName())) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                        PackageManager pm = getPackageManager();
                                        // pm.canRequestPackageInstalls() returns whether the user has granted permission to install APKs
                                        if (pm.canRequestPackageInstalls()) {


                                            UpdateUtil updateUtil = new UpdateUtil(HomeActivity.this);

                                            updateUtil.setOnUpdateStatusChangeListener(new UpdateUtil.OnUpdateStatusChangeListener() {
                                                        @Override
                                                        public void onDownloadStart() {

                                                        }

                                                        @Override
                                                        public void onDownloading(int progress) {

                                                        }

                                                        @Override
                                                        public void onDownloadCompleted() {
                                                            updateUtil.installApk();
                                                        }

                                                        @Override
                                                        public void onInstallStart() {

                                                        }

                                                        @Override
                                                        public void onDownloadCancel() {

                                                        }
                                                    })    //状态回调接口
                                                    .showDownloadNotification("正在更新", "正在下载更新...")    //显示更新通知提示
                                                    .setInstallWhenDownloadFinish(false)                    //不要下载完成后立即安装
                                                    .showDownloadProgressDialog("正在下载", "后台下载", "取消")            //显示下载进度对话框
                                                    .start(appurl,                       //开始下载
                                                            "发现更新",
                                                            content,
                                                            "开始",
                                                            "取消",
                                                            "",
                                                            false

                                                    );

                                        } else {
                                            // Jump to the permission page for installing applications for this app
                                            Uri packageURI = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
                                            // Note that this is a new API in 8.0
                                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                            startActivityForResult(intent,200);
                                        }
                                    }
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else{
                        Toast.makeText(HomeActivity.this, data.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.d("respione",error.toString()+"");
                }
            }
        });



    }


    private void initWeb(){
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

        WebSettings webSetting = mWebView.getSettings();
        String myUA = webSetting.getUserAgentString().concat("huamaoapp");
        webSetting.setUserAgentString(myUA);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
        if (getURL() == null) {
            mWebView.loadUrl(getURL());
        } else {
            mWebView.loadUrl(getURL());
        }

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void openFileChooser(
                    ValueCallback<Uri> uploadFile,
                    String acceptType,
                    String captureType) {
                Log.d("pusselece","tupian");
                //保存对应的valuecallback供选择后使用
                //通过startActivityForResult启动文件选择窗口或自定义文件选择
                mUploadMessage = uploadFile;
                selectImage();
            }
            // For Android 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

                Log.d("pusselece","tupian5.0");
                if (mUploadMessagesAboveL != null) {

                    Log.d("pusselece","111111");
                    mUploadMessagesAboveL.onReceiveValue(null);
                } else {
                    Log.d("pusselece","tupian5.0");
                    mUploadMessagesAboveL = filePathCallback;
                    selectImage();
                }
                return true;
            }

        });

    }


    private String getURL(){
        return (String) SPUtils.get(this,"url","http://103.210.237.184");
//        return "http://chuantu.biz/";
    }

    @Override
    protected void onDestroy() {

        if (mWebView != null)
            mWebView.destroy();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            } else
                return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    public static final int MSG_OPEN_TEST_URL = 0;
    public static final int MSG_INIT_UI = 1;
    private final int mUrlStartNum = 0;


    //生成随机文件名，防止上传文件后文件名重复
    public String generateRandomFilename() {
        String RandomFilename = "";
        Random rand = new Random();//生成随机数
        int random = rand.nextInt();

        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";

        RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);

        return RandomFilename;
    }

    private void selectImage() {


        CharSequence[] menuList = new CharSequence[2];
        menuList[0] = "打开图库";
        menuList[1] = "取消";
        BottomMenu.show(menuList)
                .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                    @Override
                    public boolean onClick(BottomMenu dialog, CharSequence text, int index) {

                        if(index == 0){

                            chosePicture();

                        }else{

                                if(mUploadMessagesAboveL!=null){
                                    mUploadMessagesAboveL.onReceiveValue(null);
                                    mUploadMessagesAboveL = null;
                                }
                                if(mUploadMessage!=null){
                                    mUploadMessage.onReceiveValue(null);
                                    mUploadMessage = null;}

                        }
                        return false;
                    }
                });





    }

    /**
     * 本地相册选择图片
     */
    private void chosePicture() {
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        innerIntent.setType("image/*");
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        startActivityForResult(wrapperIntent, REQUEST_CHOOSE);
    }


    /**
     * 返回文件选择
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        openPhotos = false;

        if (mUploadMessagesAboveL != null) {
            onActivityResultAboveL(requestCode, resultCode, intent);
        }

        if (mUploadMessage == null) return;

        Uri uri = null;


        if (requestCode == REQUEST_CHOOSE && resultCode == RESULT_OK) {
            uri = afterChosePic(intent);

            Luban.with(this)
                    .load(uri.getPath())
                    .ignoreBy(100)
                    .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath()+ "huamao"+ generateRandomFilename()+".jpg")
                    .filter(new CompressionPredicate() {
                        @Override
                        public boolean apply(String path) {
                            return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                        }
                    })
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件

                            mUploadMessage.onReceiveValue(Uri.parse(file.getAbsolutePath()));
                            mUploadMessage = null;

                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();

        }


        super.onActivityResult(requestCode, resultCode, intent);
    }

    /**
     * 5.0以后机型 返回文件选择
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {

        Uri[] results = null;



        if (requestCode == REQUEST_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                String dataString = data.getDataString();
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }

        mUploadMessagesAboveL.onReceiveValue(results);
        mUploadMessagesAboveL = null;
        return;
    }



    /**
     * 选择照片后结束
     *
     * @param data
     */
    private Uri afterChosePic(Intent data) {
        if (data != null) {
            final String path = data.getData().getPath();
            if (path != null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {



                return data.getData();
            } else {
                Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT).show();
            }
        }
        return null;
    }

    private String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }

    private void  cleanCache(){

//清除cookie
        CookieManager.getInstance().removeAllCookies(null);
//清除storage相关缓存
        WebStorage.getInstance().deleteAllData();;
//清除用户密码信息
        WebViewDatabase.getInstance(this).clearUsernamePassword();
//清除httpauth信息
        WebViewDatabase.getInstance(this).clearHttpAuthUsernamePassword();
//清除表单数据
        WebViewDatabase.getInstance( this).clearFormData();
//清除页面icon图标信息
        WebIconDatabase.getInstance().removeAllIcons();

        /*
        * this.getDir("appcache", 0).getPath())
this.getDir("databases", 0).getPath()
        * */

        //WebView 缓存文件
        File appCacheDir = new File(this.getDir("appcache", 0).getPath());
        File webviewCacheDir = new File(this.getDir("databases", 0).getPath());
        //删除webview 缓存目录
        if(webviewCacheDir.exists()){
            deleteFile(webviewCacheDir);
        }
        //删除webview 缓存 缓存目录
        if(appCacheDir.exists()){
            deleteFile(appCacheDir);
        }

    }
    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {


        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
        }
    }
}
